package com.miya.pay.ali;

import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.miya.exception.PayException;
import com.miya.pay.properties.AlipayProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Caixiaowei
 * @ClassName AliPayConfigure
 * @Description
 * @createTime 2021/2/7 16:03
 */
@Configuration
@Slf4j
public class AlipayConfigure {

    @Value("${custom.http.proxyHost}")
    private String proxyHost;
    @Value("${custom.http.proxyPort}")
    private int proxyPort;
    @Value("${spring.profiles.active}")
    private String activeEnv;

    @Autowired
    private AlipayProperties aliPayProperties;

    /**
     * 商家公钥证书客户端
     *
     * @param
     * @return
     * @author Caixiaowei
     * @updateTime 2021/2/8 14:50
     */
//    @Bean
//    public AlipayClient alipayClient() throws AlipayApiException {
//        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
//
//        certAlipayRequest.setServerUrl(aliPayProperties.getUrl());
//        certAlipayRequest.setAppId(aliPayProperties.getAppId());
//        certAlipayRequest.setCharset(aliPayProperties.getCharset());
//        certAlipayRequest.setFormat(aliPayProperties.getFormat());
//        certAlipayRequest.setSignType(aliPayProperties.getSignType());
//        certAlipayRequest.setPrivateKey(appRSAPrivateKey(aliPayProperties.getAppPrivateKeyPath()));
//        certAlipayRequest.setCertPath(getFileAbsolutePath(aliPayProperties.getAppCertPublicKeyPath()));
//        certAlipayRequest.setAlipayPublicCertPath(getFileAbsolutePath(aliPayProperties.getAlipayPublicCertPath()));
//        certAlipayRequest.setRootCertPath(getFileAbsolutePath(aliPayProperties.getAlipayRootCertPath()));
//
//        return new DefaultAlipayClient(certAlipayRequest);
//    }

    /**
     * @return
     */
    @Bean
    public AlipayClient alipayClient() {
        return new DefaultAlipayClient(
                aliPayProperties.getUrl(),
                aliPayProperties.getAppId(),
                aliPayProperties.getAppPrivateKey(),
                aliPayProperties.getFormat(),
                aliPayProperties.getCharset(),
                aliPayProperties.getAlipayPublicKey(),
                aliPayProperties.getSignType());
    }

//    @Bean(name = {"alipayClient"})
//    public AlipayClient alipayClientService() throws Exception {
//        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
//        //设置网关地址
//        certAlipayRequest.setServerUrl(aliPayProperties.getUrl());
//        //设置应用Id
//        certAlipayRequest.setAppId(aliPayProperties.getAppId());
//        //设置应用私钥
//        certAlipayRequest.setPrivateKey(aliPayProperties.getAppPrivateKey());
//        //设置请求格式，固定值json
//        certAlipayRequest.setFormat(aliPayProperties.getFormat());
//        //设置字符集
//        certAlipayRequest.setCharset(aliPayProperties.getCharset());
//        //设置签名类型
//        certAlipayRequest.setSignType(aliPayProperties.getSignType());
//        //如果是生产环境或者预演环境，则使用代理模式
//        if ("prod".equals(activeEnv) || "stage".equals(activeEnv) || "test".equals(activeEnv)) {
//            //设置应用公钥证书路径
//            certAlipayRequest.setCertContent(getCertContentByPath(aliPayProperties.getAppCertPath()));
//            //设置支付宝公钥证书路径
//            certAlipayRequest.setAlipayPublicCertContent(getCertContentByPath(aliPayProperties.getAlipayCertPath()));
//            //设置支付宝根证书路径
//            certAlipayRequest.setRootCertContent(getCertContentByPath(aliPayProperties.getAlipayRootCertPath()));
//            certAlipayRequest.setProxyHost(proxyHost);
//            certAlipayRequest.setProxyPort(proxyPort);
//
//        } else {
//            //local
//            String serverPath = this.getClass().getResource("/").getPath();
//            //设置应用公钥证书路径
//            certAlipayRequest.setCertPath(serverPath + aliPayProperties.getAppCertPath());
//            //设置支付宝公钥证书路径
//            certAlipayRequest.setAlipayPublicCertPath(serverPath + aliPayProperties.getAlipayCertPath());
//            //设置支付宝根证书路径
//            certAlipayRequest.setRootCertPath(serverPath + aliPayProperties.getAlipayRootCertPath());
//        }
//        return new DefaultAlipayClient(certAlipayRequest);
//    }

    private String getFileAbsolutePath(String classPath) {
        try {
            return new ClassPathResource(classPath).getFile().getAbsolutePath();
        } catch (IOException e) {
            log.error("ali pay cert path is not exist ,{}", e.getMessage());
            throw new PayException("ali pay cert path is not exist");
        }

    }


    private String appRSAPrivateKey(String classPath) {
        ClassPathResource resource = new ClassPathResource(classPath);
        try {
            FileReader in = new FileReader(resource.getFile());
            try (BufferedReader bufferedReader = new BufferedReader(in)) {
                return bufferedReader.readLine();
            }
        } catch (IOException e) {
            log.error("ali pay app private key is required ,{}", e.getMessage());
            throw new PayException("ali pay app private key is required");
        }
    }

    public String getCertContentByPath(String name) {
        InputStream inputStream = null;
        String content = null;
        try {
            inputStream = this.getClass().getClassLoader().getResourceAsStream(name);
            content = new String(FileCopyUtils.copyToByteArray(inputStream));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }
}
